﻿using System.Globalization;
using System.Text.Json;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using TianlalaHSB.Models;
using TianlalaHSB.Utils;

namespace TianlalaHSB.Views;

/// <summary>
///     MerchantAccountRecordListView.xaml 的交互逻辑
/// </summary>
public partial class MerchantAccountRecordListView : Page
{
    private Paginate<AccountRecord> _paginate;

    public MerchantAccountRecordListView()
    {
        InitializeComponent();

        _paginate = new Paginate<AccountRecord>();

        DataContext = new AccountRecordQuery
        {
            start = 1
        };
    }

    private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        e.Handled = !Number.IsInteger(e.Text);
        if (_paginate.last != 0)
            //只能控制个位数,以十位数为例10输入2: 2 102 210 12 20
            e.Handled = int.Parse(e.Text) > _paginate.last;
    }

    private void PrevPage(object sender, RoutedEventArgs e)
    {
        var startVal = Start.Text == "" ? 1 : int.Parse(Start.Text) - 1;
        Start.Text = startVal.ToString();
        SubmitButton_Click(sender, e);
    }

    private void NextPage(object sender, RoutedEventArgs e)
    {
        var startVal = Start.Text == "" ? 1 : int.Parse(Start.Text) + 1;
        Start.Text = startVal.ToString();
        SubmitButton_Click(sender, e);
    }

    private void FirstPage(object sender, RoutedEventArgs e)
    {
        Start.Text = "1";
        SubmitButton_Click(sender, e);
    }

    private void LastPage(object sender, RoutedEventArgs e)
    {
        Start.Text = _paginate.last.ToString(CultureInfo.InvariantCulture);
        SubmitButton_Click(sender, e);
    }

    private async void SubmitButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var subAcctNoVal = subAcctNo.Text.Trim();
            ;
            var startVal = Start.Text.Trim();
            if (string.IsNullOrEmpty(startVal)) throw new Exception("页码不能为空");

            var current = int.Parse(startVal);
            if (current < 1) throw new Exception("页码必须大于0");

            if (_paginate.last != 0 && current > _paginate.last) throw new Exception("已是最后一页");

            if (Validation.GetHasError(subAcctNo)) throw new Exception("资金账号格式不正确");

            if (string.IsNullOrEmpty(subAcctNoVal)) throw new Exception("资金账号不能为空");

            var startDateVal = startDate.SelectedDate.HasValue ? startDate.SelectedDate.Value : endDate.DisplayDate;
            var endDateVal = endDate.SelectedDate.HasValue ? endDate.SelectedDate.Value : endDate.DisplayDate;

            // 准备POST请求的数据 
            var postData = new AccountRecordQuery
            {
                headReqSerialNo = HttpUtil.GetHeadReqSerialNo(),
                subAcctNo = subAcctNoVal,
                startDate = startDateVal.ToString("yyyyMMdd"),
                endDate = endDateVal.ToString("yyyyMMdd"),
                fileFlag = 0,
                start = (current - 1) * 10 + 1,
                size = 10
            };

            var serialNoVal = serialNo.Text.Trim();
            if (!string.IsNullOrEmpty(serialNoVal)) postData.serialNo = serialNoVal;

            if (orderStartDate.SelectedDate.HasValue)
                postData.orderStartDate = orderStartDate.SelectedDate.Value.ToString("yyyyMMdd");

            if (orderEndDate.SelectedDate.HasValue)
                postData.orderEndDate = orderEndDate.SelectedDate.Value.ToString("yyyyMMdd");

            var orderNoVal = orderNo.Text.Trim();
            if (!string.IsNullOrEmpty(orderNoVal)) postData.orderNo = orderNoVal;

            var subOrderNoVal = subOrderNo.Text.Trim();
            if (!string.IsNullOrEmpty(subOrderNoVal)) postData.subOrderNo = subOrderNoVal;

            var responseBody = await HttpUtil.Request("03050103A1003", postData);

            var list = JsonSerializer.Deserialize<ResponseList<AccountRecord>>(responseBody);
            if (list?.dtos == null || list.dtos.Count == 0) throw new Exception("无数据");

            // 在这里处理获取到的数据，例如更新UI
            RecordListView.ItemsSource = list.dtos;

            _paginate = new Paginate<AccountRecord>(current, list.total);

            PrevButton.IsEnabled = current != 1;
            FirstButton.IsEnabled = current != 1;
            NextButton.IsEnabled = current != _paginate.last;
            LastButton.IsEnabled = current != _paginate.last;
            LastButton.Content = _paginate.last;
            JumpButton.IsEnabled = _paginate.last != 1;
            PageStackPanel.Visibility = Visibility.Visible;
        }
        catch (Exception ex)
        {
            // 处理异常，例如网络问题或无效的请求等
            MessageBox.Show(ex.Message, "提示", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void ViewButton_Click(object sender, RoutedEventArgs e)
    {
        if (sender is not Button { Tag: AccountRecord item }) return;
        // 创建并显示详情页
        var detailWindow = new AccountRecordDetailView(item)
        {
            WindowStartupLocation =
                WindowStartupLocation.CenterScreen, // CenterScreen: 屏幕中央; CenterOwner: 父窗口的中央 ;Manual: 基于Left和Top属性的设置
            Width = 600,
            Height = 500
        };
        detailWindow.ShowWindow();
    }
}